{% load i18n %}

<script type="text/javascript">

  function permissionsString(form, type) {
    var permissions = {
      'users': {},
      'groups': {}
    }
    if (typeof form === 'string'){
      form = $(form);
    }
    var data = form.serializeObject();

    /*
    * If there's the anonymous user then set it's view permission and pop it
    */
    permissions['users']['AnonymousUser'] = [];
    if (data.hasOwnProperty('view_anonymous')) {
      permissions['users']['AnonymousUser'] = ['view_resourcebase'];
      delete data['view_anonymous'];
    }
    if (data.hasOwnProperty('download_anonymous')) {
      if (typeof permissions['users']['AnonymousUser'] !== 'undefined'){
        permissions['users']['AnonymousUser'].push('download_resourcebase');
      } else {
        permissions['users']['AnonymousUser'] = ['download_resourcebase'];
      };
      delete data['download_anonymous'];
    }

    /*
    * Cycle through permissions to map the form structure perm = ['user1',',user2'] to
    * the geonode user = ['perm1','perm2'], the same for groups
    */
    var default_permissions = [
      'view_resourcebase_users',
      'view_resourcebase_groups',
      'download_resourcebase_users',
      'download_resourcebase_groups',
      'change_resourcebase_metadata_users',
      'change_resourcebase_metadata_groups',
      'change_layer_data_users',
      'change_layer_data_groups',
      'change_layer_style_users',
      'change_layer_style_groups',
      'manage_resourcebase_users',
      'manage_resourcebase_groups'
    ];
    $(default_permissions).each(function(index, perm) {
      var perms_to_assign = [];
      var perm_users_found = false;
      var perm_groups_found = false;
      if(perm.endsWith("_users")) {
          perms_to_assign = [perm.substring(0, perm.length - "_users".length)];
          perm_users_found = true;
      }
      if(perm.endsWith("_groups")) {
          perms_to_assign = [perm.substring(0, perm.length - "_groups".length)];
          perm_groups_found = true;
      }
      if(perm.startsWith('manage_resourcebase')){
          perms_to_assign = ['change_resourcebase', 'delete_resourcebase', 'change_resourcebase_permissions', 'publish_resourcebase'];
      }
      
      if (perm_users_found || perm_groups_found) {
        var perm_key = perm_users_found ? 'users' : 'groups';
        var d_perms = [];
        $($('#' + perm).select2('data')).each(function (index, value) { d_perms.push(value.id); });
        if (d_perms instanceof Array) {
          for (var i=0;i<d_perms.length;i++){
            var perm_value = d_perms[i];
            for(var j=0;j< perms_to_assign.length;j++){
              if(permissions[perm_key].hasOwnProperty(perm_value)){
                permissions[perm_key][perm_value].push(perms_to_assign[j]);
              }else{
                permissions[perm_key][perm_value] = [perms_to_assign[j]];
              }
            }
          }
        } else {
          for (var i=0;i<d_perms.split(',').length;i++){
            var perm_value = d_perms.split(',')[i];
            for(var j=0;j< perms_to_assign.length;j++){
              if(permissions[perm_key].hasOwnProperty(perm_value)){
                permissions[perm_key][perm_value].push(perms_to_assign[j]);
              }else{
                permissions[perm_key][perm_value] = [perms_to_assign[j]];
              }
            }
          }
        }
      }
    });

    return permissions
  };

  $(function() {
    $('#permissions-body').ready(function(){
      {% if resource %}
      $.ajax(
        "{% url "resource_permissions" resource.id %}",
        {
          success: function(data){
            var users = {
              view_resourcebase: [],
              download_resourcebase: [],
              change_resourcebase_metadata: [],
              change_layer_data: [],
              change_layer_style: [],
              manage_resourcebase: [],
            };

            // let's initialize the anyone flags to false, if there's the AnonymousUser
            // they will be chacked later
            $('#perms_view_anyone').prop('checked', false);
            $('#perms_download_resourcebase_anyone').prop('checked', false);

            /*
            * Compile the users fields after receiving the current permissions status from the server
            */
            var perms = $.parseJSON($.parseJSON(data).permissions);

            var perms_users = perms.users;

            /*
            * If there is the group anonymous then treas it as it is the AnonymousUser
            * since the server doesn't explicitly send the users that belongs to a group with permissions
            */
            if (perms.groups.hasOwnProperty('anonymous')){
              perms_users.AnonymousUser = perms.groups.anonymous;
            }

            for (var user in perms_users){
              var user_perms = perms_users[user];
              if (user === 'AnonymousUser'){
                if(user_perms.indexOf('view_resourcebase') > -1){
                  $('#perms_view_anyone').prop('checked', true);
                }
                if(user_perms.indexOf('download_resourcebase') > -1){
                  $('#perms_download_resourcebase_anyone').prop('checked', true);
                }
              }else{
                for (var i=0;i<user_perms.length;i++){
                  if(['change_resourcebase', 'delete_resourcebase', 'change_resourcebase_permissions', 'publish_resourcebase'].indexOf(user_perms[i]) >= 0){
                    if(users['manage_resourcebase'].indexOf(user)<0){
                      users['manage_resourcebase'].push(user);
                    }
                  }else{
                    if(users.hasOwnProperty(user_perms[i])){
                      users[user_perms[i]].push(user);
                    }
                  }
                }
              }
            }

            // If "anyone" is checked then don't show all the users in the view perms field
            // if (perms_users.hasOwnProperty('AnonymousUser')
            //   && perms_users['AnonymousUser'].indexOf('view_resourcebase') > -1){
            //   users.view_resourcebase=[]
            // };

            // if (perms_users.hasOwnProperty('AnonymousUser')
            //   && perms_users['AnonymousUser'].indexOf('download_resourcebase') > -1){
            //   users.download_resourcebase=[]
            // };

            if (typeof user_perms === 'undefined') {
              user_perms = [];
            }

            for (var perm in users){
              if(['change_resourcebase', 'delete_resourcebase', 'change_resourcebase_permissions', 'publish_resourcebase'].indexOf(user_perms[i]) >= 0){
                if(users['manage_resourcebase'].indexOf(user)<0){
                  users['manage_resourcebase'].push(user);
                }
              }else{
                if(users.hasOwnProperty(user_perms[i])){
                  users[user_perms[i]].push(user);
                }
              }
              addSelectUsers('#' + perm + '_users', users[perm]);
            }

            /*
            * Compile the groups fields after receiving the current permissions status from the server
            */
            var groups = {
              view_resourcebase: [],
              download_resourcebase: [],
              change_resourcebase_metadata: [],
              change_layer_data: [],
              change_layer_style: [],
              manage_resourcebase: []
            };

            var perms_groups = perms.groups;
            for (var group in perms_groups){
              if (group !== 'anonymous'){
                var group_perms = perms_groups[group];
                for (var i=0;i<group_perms.length;i++){
                  if(['change_resourcebase', 'delete_resourcebase', 'change_resourcebase_permissions', 'publish_resourcebase'].indexOf(group_perms[i]) >= 0){
                    if(groups['manage_resourcebase'].indexOf(group)<0){
                      groups['manage_resourcebase'].push(group);
                    }
                  }else{
                    if(groups.hasOwnProperty(group_perms[i])){
                      groups[group_perms[i]].push(group);
                    }
                  }
                }
              }
            }

            for (var perm in groups){
              addSelectGroups('#' + perm + '_groups', groups[perm]);
            }
          }
        }
      );
      {% else %}
        addSelectUsers('.user-select', []);
        addSelectGroups('.group-select', []);
      {% endif %}
    });

    function addSelectUsers(id, default_perms){
      $.fn.select2.amd.require([
        'select2/utils',
        'select2/data/ajax',
        'select2/data/minimumInputLength'
      ],
      function (Utils, AjaxAdapter, MinimumInputLength) {

        function UsersAjaxAdapter($el, options) {
          UsersAjaxAdapter.__super__.constructor.call(this, $el, options);
        }

        Utils.Extend(UsersAjaxAdapter, AjaxAdapter);

        var initialValues = [];
        
        // In case resources are private we add the current user
        {% if DEFAULT_ANONYMOUS_VIEW_PERMISSION is False %}
            {% if request.resolver_match.url_name  == 'layer_upload' or request.resolver_match.url_name  == 'document_upload' %}
                var initialValues = [{name: "{{request.user}}", id:"{{request.user}}"}];
            {% endif %}
        {% endif %}
        
        $(default_perms).each(function (index, perm) {
            initialValues.push({ id: perm, name: perm });
        });

        UsersAjaxAdapter.prototype.current = function (callback) {
          var data = [];
          UsersAjaxAdapter.__super__.current.call(this, function (d) { data = d });
          _.each(initialValues, function (el) { data.push(el); })
          callback(data);
        }

        UsersAjaxAdapter.prototype.unselect = function (data) {
          initialValues = _.reject(initialValues, function (el) { return el.id == data.id });
          UsersAjaxAdapter.__super__.unselect.call(this, data);
        }

        $(id).select2({
          ajax: {
            url: '{% url "account_ajax_lookup" %}',
            dataType: 'json',
            delay: 250,
            type: "POST",
            data: function (params) {
              return {
                query: params.term,
                page: params.page || 1,
                pageSize: 9
              };
            },
            processResults: function (data, params) {
              if (data.users.length)
                return {
                  results: data.users.map(d => ({ id: d.username, name: d.username })),
                  pagination: {
                    // more: !!data.paging.next
                    more: false
                  }
                };
              else
                return {
                  results: [],
                  pagination: {
                    more: false
                  }
                };
            },
            cache: false
          },
          placeholder: '{% trans "Choose users..." %}',
          minimumInputLength: 1,
          multiple: true,
          width: 'copy',
          containerCssClass: function (e) {
            return $(e).attr('required') ? 'required' : '';
          },
          dataAdapter: Utils.Decorate(UsersAjaxAdapter, MinimumInputLength),
          templateResult: function (item) { return (item.loading) ? item.text : item.name; },
          templateSelection: function (item) { return item.name; }
        });
      });
    }

    function addSelectGroups(id, default_perms){
      $.fn.select2.amd.require([
        'select2/utils',
        'select2/data/ajax',
        'select2/data/minimumInputLength'
      ],
      function (Utils, AjaxAdapter, MinimumInputLength) {

        function GroupsAjaxAdapter($el, options) {
          GroupsAjaxAdapter.__super__.constructor.call(this, $el, options);
        }

        Utils.Extend(GroupsAjaxAdapter, AjaxAdapter);

        var initialValues = [];
        $(default_perms).each(function (index, perm) {
            initialValues.push({ id: perm, name: perm });
        });

        GroupsAjaxAdapter.prototype.current = function (callback) {
          var data = [];
          GroupsAjaxAdapter.__super__.current.call(this, function (d) { data = d });
          _.each(initialValues, function (el) { data.push(el); })
          callback(data);
        }

        GroupsAjaxAdapter.prototype.unselect = function (data) {
          initialValues = _.reject(initialValues, function (el) { return el.id == data.id });
          GroupsAjaxAdapter.__super__.unselect.call(this, data);
        }

        $(id).select2({
          ajax: {
            url: '{% url "account_ajax_lookup" %}',
            dataType: 'json',
            delay: 250,
            type: "POST",
            data: function (params) {
              return {
                query: params.term,
                page: params.page || 1,
                pageSize: 9
              };
            },
            processResults: function (data, params) {
              if (data.groups.length)
                return {
                  results: data.groups.map(d => ({ id: d.name, name: d.title })),
                  pagination: {
                    // more: !!data.paging.next
                    more: false
                  }
                };
              else
                return {
                  results: [],
                  pagination: {
                    more: false
                  }
                };
            },
            cache: false
          },
          placeholder: '{% trans "Choose groups..." %}',
          minimumInputLength: 1,
          multiple: true,
          width: 'copy',
          containerCssClass: function (e) {
            return $(e).attr('required') ? 'required' : '';
          },
          dataAdapter: Utils.Decorate(GroupsAjaxAdapter, MinimumInputLength),
          templateResult: function (item) { return (item.loading) ? item.text : item.name; },
          templateSelection: function (item) { return item.name; }
        });
      });
    }

    var perms_submit = function() {
      var form = $(this);
      var action = form.attr("action");
      var permissions = permissionsString(form, 'base');
      $.ajax(
        {
          type: "POST",
          url: action,
          data: JSON.stringify(permissions),
          beforeSend: function(){
               // Handle the beforeSend event
               try {
                   $("#_perms_processing").modal("show");
               } catch(err) {
                   console.log(err);
               }
          },
          complete: function(){
               // Handle the complete event
               try {
                   $("#_perms_processing").modal("hide");
               } catch(err) {
                   console.log(err);
               }
          },
          success: function(data) {
            $("#modal_perms").modal("hide");
            message = JSON.parse(data);
            title = "";
            body = message.message;
            if (message.success) {
                title = "OK";
            } else {
                title = "Warning";
            }
            $("#_permissions_feedbacks").find('.modal-title').text(title);
            $("#_permissions_feedbacks").find('.modal-body').text(body);
            $("#_permissions_feedbacks").modal("show");
            $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
          }, /* - END success - */
          cache: false
        }
      ).fail(function (jqXHR, textStatus, error) {
            // Handle error here
            $("#modal_perms").modal("hide");
            message = JSON.parse(jqXHR.responseText);
            body = message.message;
            title = "Error";
            $("#_permissions_feedbacks").find('.modal-title').text(title);
            $("#_permissions_feedbacks").find('.modal-body').text(body);
            $("#_permissions_feedbacks").modal("show");
            $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
      });
      return false;
    };

    $("#perms_submit").click(function(){
        $("#permission_form").submit();
    });

    {% if resource %}
        $("#permission_form").submit(perms_submit);
    {% endif %}

    $("#security_refresh").click(function(){
        $.ajax(
          {
            type: "POST",
            url: "{% url 'invalidate_permissions_cache' %}",
            dataType: 'json',
            data: { uuid: "{{ resource.uuid }}" },
            beforeSend: function(){
                 // Handle the beforeSend event
                 try {
                     $("#_perms_processing").modal("show");
                 } catch(err) {
                     console.log(err);
                 }
            },
            complete: function(){
                 // Handle the complete event
                 try {
                     $("#_perms_processing").modal("hide");
                 } catch(err) {
                     console.log(err);
                 }
            },
            success: function(data) {
              $("#modal_perms").modal("hide");
              message = data;
              title = "";
              body = message.message;
              if (message.success) {
                  title = "OK";
              } else {
                  title = "Warning";
              }
              $("#_permissions_feedbacks").find('.modal-title').text(title);
              $("#_permissions_feedbacks").find('.modal-body').text(body);
              $("#_permissions_feedbacks").modal("show");
              $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
            },
            error: function(jqXHR, textStatus){
                try {
                    if(textStatus === 'timeout')
                    {
                        $("#_permissions_feedbacks").find('.modal-title').text('Timeout');
                        $("#_permissions_feedbacks").find('.modal-body').text('Failed from timeout: Could not create Thumbnail');
                        $("#_permissions_feedbacks").modal("show");
                    } else {
                        $("#_permissions_feedbacks").find('.modal-title').text('Error: ' + textStatus);
                        $("#_permissions_feedbacks").find('.modal-body').text('Could not set Layer Permissions');
                        $("#_permissions_feedbacks").modal("show");
                    }
                } catch(err) {
                    console.log(err);
                } finally {
                    return true;
                }
            },
            cache: false,
            timeout: 60000
          }
        ).fail(function (jqXHR, textStatus, error) {
              // Handle error here
              $("#modal_perms").modal("hide");
              message = JSON.parse(jqXHR.responseText);
              body = message.message;
              title = "Error";
              $("#_permissions_feedbacks").find('.modal-title').text(title);
              $("#_permissions_feedbacks").find('.modal-body').text(body);
              $("#_permissions_feedbacks").modal("show");
              $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
        });
        return false;
    });

    $("#attributes_sats_refresh").click(function(){
        $.ajax(
          {
            type: "POST",
            url: "{% url 'attributes_sats_refresh' %}",
            dataType: 'json',
            data: { uuid: "{{ resource.uuid }}" },
            success: function(data) {
              $("#modal_perms").modal("hide");
              message = data;
              title = "";
              body = message.message;
              if (message.success) {
                  title = "OK";
              } else {
                  title = "Warning";
              }
              $("#_permissions_feedbacks").find('.modal-title').text(title);
              $("#_permissions_feedbacks").find('.modal-body').text(body);
              $("#_permissions_feedbacks").modal("show");
              $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
            },
            cache: false
          }
        ).fail(function (jqXHR, textStatus, error) {
              // Handle error here
              $("#modal_perms").modal("hide");
              message = JSON.parse(jqXHR.responseText);
              body = message.message;
              title = "Error";
              $("#_permissions_feedbacks").find('.modal-title').text(title);
              $("#_permissions_feedbacks").find('.modal-body').text(body);
              $("#_permissions_feedbacks").modal("show");
              $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
        });
        return false;
    });

    $("#tiledlayer_refresh").click(function(){
        $.ajax(
          {
            type: "POST",
            url: "{% url 'invalidate_tiledlayer_cache' %}",
            dataType: 'json',
            data: { uuid: "{{ resource.uuid }}" },
            success: function(data) {
              $("#modal_perms").modal("hide");
              message = data;
              title = "";
              body = message.message;
              if (message.success) {
                  title = "OK";
              } else {
                  title = "Warning";
              }
              $("#_permissions_feedbacks").find('.modal-title').text(title);
              $("#_permissions_feedbacks").find('.modal-body').text(body);
              $("#_permissions_feedbacks").modal("show");
              $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
            },
            cache: false
          }
        ).fail(function (jqXHR, textStatus, error) {
              // Handle error here
              $("#modal_perms").modal("hide");
              message = JSON.parse(jqXHR.responseText);
              body = message.message;
              title = "Error";
              $("#_permissions_feedbacks").find('.modal-title').text(title);
              $("#_permissions_feedbacks").find('.modal-body').text(body);
              $("#_permissions_feedbacks").modal("show");
              $('#_permissions_feedbacks').on('hidden.bs.modal', function () { location.reload(); });
        });
        return false;
    });

    $("#_bulk_permissions").on('hidden.bs.modal', function (e) {
      $('#bulk_perms_message').addClass("hidden");
    });
  });
</script>
